package com.itqf.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itqf.bean.DtsRole;
import com.itqf.bean.DtsRoleExample;
import com.itqf.dto.CommonsDto;
import com.itqf.dto.PermissionDto;
import com.itqf.mapper.DtsRoleMapper;
import com.itqf.service.DtsAdminService;
import com.itqf.service.DtsPermissionService;
import com.itqf.service.DtsRoleService;
import com.itqf.util.ResponseUtil;
import com.itqf.utils.AdminResponseCode;
import com.itqf.utils.AdminResponseUtil;
import com.itqf.utils.Permission;
import com.itqf.utils.PermissionUtil;
import com.itqf.vo.PermVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * projectName: gp_manage
 *
 * @author: 赵伟风
 * time: 2021/8/17 11:00
 * description:
 */
@Service
public class DtsRoleServiceImpl implements DtsRoleService {

    @Autowired
    private DtsRoleMapper dtsRoleMapper;

    @Autowired
    private DtsAdminService dtsAdminService;


    @Autowired
    private DtsPermissionService dtsPermissionService;

    /**
     * 根据角色id查询角色名称！
     *
     * @param roleIds
     * @return
     */
    @Override
    public List<String> findRoleNameByRoleIds(Integer[] roleIds) {

        //1.查询数据
        DtsRoleExample example = new DtsRoleExample();
        DtsRoleExample.Criteria criteria = example.createCriteria();

        /**
         * id in  enabled = 1  deleted 0
         */

        criteria.andIdIn(Arrays.asList(roleIds));

        criteria.andEnabledEqualTo(true);

        criteria.andDeletedEqualTo(false);

        List<DtsRole> roleList =   dtsRoleMapper.selectByExample(example);

        if (roleList == null || roleList.size() == 0) {

            return null;
        }

        //2.返回结果
        List<String> roleNames = new ArrayList<>();

        for (DtsRole dtsRole : roleList) {
            roleNames.add(dtsRole.getName());
        }

        return roleNames;
    }

    /**
     * 是不是管理员
     * 判断依据： 角色命中包含管理员
     *
     * @param roleIds
     * @return
     */
    @Override
    public boolean isAdminRole(Integer[] roleIds) {


        List<String> roleNames = findRoleNameByRoleIds(roleIds);

        if (roleNames == null || roleNames.size() == 0) {

            return false;
        }


        for (String roleName : roleNames) {

            if (roleName.contains("管理员")) {

                return true;
            }
        }

        return false;
    }

    /**
     * 查询全部role数据
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> findRoleAll() {

        //1.查询全部数据
        //查询条件传入空证明是查询全部数据
        List<DtsRole> dtsRoles = dtsRoleMapper.selectByExample(null);

        //2.封装数据

        List<Map<String,Object>> data  = new ArrayList<>();
        for (DtsRole dtsRole : dtsRoles) {
            Map<String,Object> map = new HashMap<>();
            map.put("value", dtsRole.getId());
            map.put("label", dtsRole.getName());
            data.add(map);
        }

        return data;
    }



    /**
     * 分页查询角色
     *
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> findRoleByPage(CommonsDto dto) {


        //1.设置分页数据
        PageHelper.startPage(dto.getPage(), dto.getLimit());
        //2.查询数据     注意: 动态条件 rolename  / 是否可用  / 逻辑删除

        DtsRoleExample roleExample = new DtsRoleExample();
        DtsRoleExample.Criteria criteria = roleExample.createCriteria();

        criteria.andEnabledEqualTo(true);
        criteria.andDeletedEqualTo(false);

        if (dto.getRolename() != null && !dto.getRolename().equals("")){
            criteria.andNameLike("%"+dto.getRolename()+"%");
        }

        List<DtsRole> dtsRoles = dtsRoleMapper.selectByExample(roleExample);
        //3.封装PageInfo

        PageInfo<DtsRole> pageInfo = new PageInfo<>(dtsRoles);

        //4.封装返回数据   total  / items

        Map<String,Object> data = new HashMap<>();
        data.put("total", pageInfo.getTotal());
        data.put("items", pageInfo.getList());

        return data;
    }

    /**
     * 插入role数据
     *
     * @param dtsRole
     * @return
     */
    @Override
    public Object insertRole(DtsRole dtsRole) {

        //1.判断角色是否存在 adminresponseCode 如果他没有  responseUtils.fail(-1,"错误描述")

        DtsRoleExample roleExample = new DtsRoleExample();
        DtsRoleExample.Criteria criteria = roleExample.createCriteria();

        criteria.andNameEqualTo(dtsRole.getName());
        //非逻辑删除的需要判断
        //enable = true 或者 false 都不能创建
        criteria.andDeletedEqualTo(false);

        long count = dtsRoleMapper.countByExample(roleExample);

        if (count>0) {

            return AdminResponseUtil.fail(AdminResponseCode.ROLE_NAME_EXIST);
        }


        //2.插入数据
        //完整数据  添加时间 逻辑删除  是否可用
        //插入数据 [数据回显]

        dtsRole.setAddTime(new Date());
        dtsRole.setEnabled(true);
        dtsRole.setDeleted(false);

        int rows = dtsRoleMapper.insertDtsRole(dtsRole);

        //3.封装结果

        //rows>0  responseUtils.ok(dtsRole)

        if (rows>0) {

            return ResponseUtil.ok(dtsRole);
        }

        return ResponseUtil.fail(-1, "插入用户失败!");
    }

    /**
     * 修改role数据
     *
     * @param dtsRole
     * @return
     */
    @Override
    public Object updateRoleById(DtsRole dtsRole) {

        //1.查询要修改后的角色名是否存在 name =  id !=  delete = false
        DtsRoleExample roleExample = new DtsRoleExample();
        DtsRoleExample.Criteria criteria = roleExample.createCriteria();

        criteria.andNameEqualTo(dtsRole.getName());
        //非逻辑删除的需要判断
        //enable = true 或者 false 都不能创建
        criteria.andDeletedEqualTo(false);
        criteria.andIdNotEqualTo(dtsRole.getId());

        long count = dtsRoleMapper.countByExample(roleExample);

        if (count>0) {

            return AdminResponseUtil.fail(AdminResponseCode.ROLE_NAME_EXIST);
        }

        //2.超级管理员角色不能修改 adminresponseCode有状态

        Integer[] roleIds = new Integer[]{dtsRole.getId()};

        boolean isSuper = false;

        if (roleIds != null || roleIds.length > 0)
        {
            List<String> permissions = dtsPermissionService.findPermissionsByRoleIds(roleIds);

            if (permissions != null && permissions.size() >0) {

                for (String permission : permissions) {

                    if (permission.equalsIgnoreCase("*")) {

                        isSuper = true;
                    }
                }

            }
        }

        if (isSuper) {

            return AdminResponseUtil.fail(AdminResponseCode.ROLE_SUPER_SUPERMISSION);
        }

        //3.修改即可 rows > 0
        dtsRole.setUpdateTime(new Date());

        int rows = dtsRoleMapper.updateByPrimaryKeySelective(dtsRole);


        if (rows > 0){

            return ResponseUtil.ok();
        }


        return ResponseUtil.fail(-1,"角色更新失败!");
    }

    /**
     * 删除角色名
     *
     * @param dtsRole
     * @return
     */
    @Override
    public Object deleteRoleById(DtsRole dtsRole) {

        //2.超级管理员不可删除

        Integer[] roleIds = new Integer[]{dtsRole.getId()};

        boolean isSuper = false;

        if (roleIds != null || roleIds.length > 0)
        {
            List<String> permissions = dtsPermissionService.findPermissionsByRoleIds(roleIds);

            if (permissions != null && permissions.size() >0) {

                for (String permission : permissions) {

                    if (permission.equalsIgnoreCase("*")) {

                        isSuper = true;
                    }
                }

            }
        }

        if (isSuper) {

            return AdminResponseUtil.fail(AdminResponseCode.ROLE_SUPER_SUPERMISSION);
        }

        //3.非超级管理员,有用使用不可删除!
        boolean use = dtsAdminService.findAdminUseRoleId(dtsRole.getId());

        if (use){
            //用户正在使用角色
            return ResponseUtil.fail(-1, "角色删除失败!其他用户正在使用!");
        }

        //3.删除角色表 逻辑删除
        //1.删除相关的权限 逻辑删除
        dtsRole.setDeleted(true);
        int rows = dtsRoleMapper.updateByPrimaryKeySelective(dtsRole);

        if (rows > 0){
            return ResponseUtil.ok();
        }

        return ResponseUtil.fail(-1, "删除角色失败!");
    }

    /**
     * 赋权列表
     *
     *
     * @param permissionList
     * @param roleId
     * @return
     */
    @Override
    public Object findPermissionList(List<Permission> permissionList, int roleId) {


        //1.查询系统中有的权限
        List<PermVo> systemPermissions = PermissionUtil.listPermVo(permissionList);
        //程序的全部权限
        Set<String> listPermissionString = PermissionUtil.listPermissionString(permissionList);

        //2.查询角色对应的权限

        Integer[] roleIds = new Integer[]{roleId};

        boolean isSuper = false;

        List<String> permissions = null;

        if (roleIds != null || roleIds.length > 0)
        {
            permissions = dtsPermissionService.findPermissionsByRoleIds(roleIds);

            if (permissions != null && permissions.size() >0) {

                for (String permission : permissions) {

                    if (permission.equalsIgnoreCase("*")) {

                        isSuper = true;
                    }
                }

            }
        }

        List<String> assignedPermissions = new ArrayList<>();

        if (isSuper) {
            //超级管理员
            for (String permission : listPermissionString) {
                assignedPermissions.add(permission);
            }

        }else{
            //返回我有的权限
            assignedPermissions.addAll(permissions);
        }

        //3.封装返回
        Map<String,Object> data = new HashMap<>();
        data.put("systemPermissions", systemPermissions);
        data.put("assignedPermissions", assignedPermissions);

        return data;
    }

    /**
     * 修改角色权限
     *
     * @param permissionDto
     * @return
     */
    @Override
    public Object updateRolePermission(PermissionDto permissionDto) {


        //1.超级管理员不能修改
        Integer[] roleIds = new Integer[]{permissionDto.getRoleId()};

        boolean isSuper = false;

        List<String> permissions = null;

        if (roleIds != null || roleIds.length > 0)
        {
            permissions = dtsPermissionService.findPermissionsByRoleIds(roleIds);

            if (permissions != null && permissions.size() >0) {

                for (String permission : permissions) {

                    if (permission.equalsIgnoreCase("*")) {

                        isSuper = true;
                    }
                }

            }
        }

        if (isSuper) {

            return AdminResponseUtil.fail(AdminResponseCode.ROLE_SUPER_SUPERMISSION);
        }

        //2.删除角色对应权限
        dtsPermissionService.deletePermissionsByRoleId(permissionDto.getRoleId());

        //3.添加角色对应权限
        dtsPermissionService.savePermissionsByRoleId(permissionDto);

        return ResponseUtil.ok();
    }

    /**
     * 是不是超级管理员
     *
     * @param roleIds 角色id
     * @return true 是/ false不是
     */
    @Override
    public boolean checkSuper(Integer... roleIds) {

        if (roleIds != null || roleIds.length > 0)
        {
            List<String> permissions  = dtsPermissionService.findPermissionsByRoleIds(roleIds);

            if (permissions != null && permissions.size() >0) {

                for (String permission : permissions) {

                    if (permission.equalsIgnoreCase("*")) {

                         return true;
                    }
                }

            }
        }

        return false;
    }


}
